﻿using System;
using System.Collections.Generic;
using System.Linq.Expressions;
using System.Threading.Tasks;
using System.Web.Mvc;
using Yz.Base;
//using Yz.Core.Caches;
using Yz.Core.Extensions;
using Yz.DataAccess.DataCache.Interface;
using Yz.DataAccess.DbAccessses.Interface;
using Yz.Model.Constants;
using Yz.Model.Dal;
using Yz.Model.Entities;
using Yz.Model.Views;
using Yz.Mvc.Filters;

namespace Yz.Web.Controllers
{
    [AllowAnonymous]
    [RoleAuthorize(Roles = UserRoleName.User)]
    public class AccountController : BaseWebController
    {
        private readonly IUserAccess _userAccess;
        private readonly IUserCache _userCache;
        private readonly IShareCodeAccess _shareCodeAccess;
        //private readonly IAuthorizeCache _authorizeCache;
        public AccountController(IUserAccess userAccess, IUserCache userCache,
            IShareCodeAccess shareCodeAccess
            //, IAuthorizeCache authorizeCache
            )
        {
            _userAccess = userAccess;
            _userCache = userCache;
            _shareCodeAccess = shareCodeAccess;
            //_authorizeCache = authorizeCache;
        }
        /// <summary>
        /// 未登录状态下的首页
        /// </summary>
        /// <returns></returns> 
        [Route("account/index")]
        [Route("Home/index")]
        public async Task<ActionResult> Index()
        {
            var aa = YzContext.GetInstance().GetDbDictionary();
            //    var ss = new User().GetDbColDictionary();
            //int count111 = _authorizeCache.GetLoginLockTime("18952265594", 1);
            //count111 = await _authorizeCache.GetLoginLockTimeAsync("18952265594", 1);
            //var isOke = _authorizeCache.UpdateLoginLock("18952265594", 1, count111 + 1);
            //isOke = await _authorizeCache.UpdateLoginLockAsync("18952265594", 1, count111 + 1);
            //var unifyToken = _authorizeCache.CreateUnifyToken(0, 1);
            //unifyToken = await _authorizeCache.CreateUnifyTokenAsync(0, 1);
            //var tokenOk = _authorizeCache.ValidateUnifyToken(0, 1, "");
            //tokenOk = await _authorizeCache.ValidateUnifyTokenAsync(0, 1, "");
            //List<ShareCode> shareCodeList = new List<ShareCode>();
            //for (int i = 50000; i < 100000; i++)
            //{
            //    shareCodeList.Add(new ShareCode() { UId = i, Code = i.IdToCode() });
            //}
            //int count = _shareCodeAccess.BatchAdd(shareCodeList);

            List<ParaOrder<User>> orders = new List<ParaOrder<User>>
            {
                new ParaOrder<User>()
                {
                    Order = p => new { p.CreateTime },
                    IsAsc = true
                },
                new ParaOrder<User>()
                {
                    Order = p => new { p.StatusType },
                    IsAsc = true
                }
            };
            var userInfo = new Admin() { LoginName = "sdfsdf", PassWord = "1111" };
            string aaa = "bbb";
            var returnCode = _userAccess.Add(new User()
            {
                Telephone = aaa,
                Password = aaa.ToMd5Hash(),
                QQ = aaa,
                UserName = aaa
            });
            var u = _userAccess.AddGet(new User()
            {
                Telephone = aaa,
                Password = aaa.ToMd5Hash(),
                QQ = aaa,
                UserName = aaa
            });

            List<Expression<Func<User, bool>>> whereList = new List<Expression<Func<User, bool>>>();
            Expression<Func<User, bool>> where = p => p.StatusType == StatusType.Enable;
            whereList.Add(p => p.UserName.Contains(aaa));
            whereList.Add(p => p.Telephone.Contains(aaa));
            var list = await _userAccess.GetListByPageAsync<VmUser>(p => true, new ParaPage() { SkipNum = 0, TakeNum = 10 }, orders);
            var list3 = _userAccess.GetListByPage<VmUser>(p => p.UserName == "", new ParaPage() { SkipNum = 0, TakeNum = 10 }, orders);
            var list1 = _userCache.GetListByPage<VmUser>(p => p.UserName == aaa, new ParaPage() { SkipNum = 0, TakeNum = 10 }, orders);
            list1 = _userCache.GetListByPage<VmUser>(p => p.UserName == aaa && p.UserPhoto == userInfo.PassWord, new ParaPage() { SkipNum = 0, TakeNum = 10 }, orders);
            list1 = _userCache.GetListByPage<VmUser>(p => p.UserName == userInfo.LoginName && p.UserPhoto == userInfo.PassWord, new ParaPage() { SkipNum = 0, TakeNum = 10 }, orders);
            list1 = _userCache.GetListByPage<VmUser>(where, new ParaPage() { SkipNum = 0, TakeNum = 10 }, orders);
            list1 = await _userCache.GetListByPageAsync<VmUser>(whereList, new ParaPage() { SkipNum = 0, TakeNum = 10 }, orders);
            var list2 = _userAccess.GetUnionListByPage<VmUser>(whereList, new ParaPage() { SkipNum = 0, TakeNum = 10 }, orders);
            return View();
        }

        #region 登录注销
        /// <summary>
        /// 登录
        /// </summary>
        /// <returns></returns> 
        public ActionResult Login()
        {
            return View();
        }
        [HttpPost]
        public JsonResult LoginUser(string lgnName, string lgnPwd)
        {
            if (string.IsNullOrEmpty(lgnName) || string.IsNullOrEmpty(lgnPwd))
            {
                return Json(new { suc = false, msg = "用户名密码不能为空！" });
            }
            lgnPwd = lgnPwd.ToMd5Hash();
            var user = _userAccess.GetModel<VmUser>(p => p.Telephone == lgnName && p.Password == lgnPwd);
            if (user != null)
            {
                base.SignIn(new List<string> { UserRoleName.User }, user);
                return Json(new { suc = true, msg = "登录成功！" });
            }
            return Json(new { suc = false, msg = "用户名或者密码错误！" });
        }
        /// <summary>
        /// 退出
        /// </summary>
        /// <returns></returns> 
        public ActionResult LogOff()
        {
            AuthenticationManager.SignOut();
            return Redirect("/Account/Login");
        }

        public JsonResult GetUserList()
        {

            var retList = new ReturnList<VmUser>()
            {
                List = new List<VmUser> { },
                Total = 1
            };
            return Json(retList.ToVmPageList(), JsonRequestBehavior.AllowGet);
        }
        #endregion

        /// <summary>
        /// 错误页面
        /// </summary>
        /// <returns></returns> 
        public ActionResult Error()
        {
            return View();
        }
        /// <summary>
        /// 非法登录
        /// </summary>
        /// <returns></returns> 
        public ActionResult Illegal()
        {
            return View();
        }


        #region 注册 
        public ActionResult Register()
        {
            return View();
        }
        [HttpPost]
        public JsonResult RegisterUser(string lgnName, string lgnPwd, string lgnNewPwd, string qq, string lgnTelCode)
        {
            if (string.IsNullOrEmpty(lgnName))
            {
                return Json(new { suc = false, msg = "请输入手机号" });
            }
            if (string.IsNullOrEmpty(lgnPwd))
            {
                return Json(new { suc = false, msg = "请输入密码" });
            }
            if (lgnNewPwd != lgnPwd)
            {
                return Json(new { suc = false, msg = "两次密码不一致" });
            }
            if (string.IsNullOrEmpty(lgnTelCode))
            {
                return Json(new { suc = false, msg = "请输入短信验证码" });
            }
            //var smvCode = _smvCodeAccess.GetSmvCode(lgnTelCode);
            //if (smvCode == null || smvCode.EffectiveTime < DateTime.Now)
            //{
            //    return Json(new { suc = false, msg = "验证码无效！" });
            //}
            var returnCode = _userAccess.Add(new User()
            {
                Telephone = lgnName,
                Password = lgnPwd.ToMd5Hash(),
                QQ = qq,
                UserName = lgnName
            }, p => p.Telephone != lgnName);
            if (returnCode == ReturnCode.Success)
            {
                return Json(new { suc = true, msg = "注册成功！" });
            }
            else if (returnCode == ReturnCode.Exit)
            {
                return Json(new { suc = false, msg = "该用户已存在！" });
            }
            return Json(new { suc = false, msg = "注册失败！" });
        }
        #endregion


        #region 重置密码 
        public ActionResult ResetPwd()
        {
            return View();
        }
        #endregion 


    }
}